package com.deyuanyun.pic.settings.support.interceptor;

import com.alibaba.fastjson.JSON;
import com.deyuanyun.pic.common.util.ajax.AjaxMessageResult;
import com.deyuanyun.pic.common.util.ajax.AjaxResponse;
import com.deyuanyun.pic.common.util.ajax.AjaxSupport;
import com.deyuanyun.pic.common.util.web.RequestResponseContext;
import com.deyuanyun.pic.settings.controller.dto.UserSessionVO;
import com.deyuanyun.pic.settings.support.cache.SessionCacheSupport;
import org.apache.commons.lang.StringUtils;

import javax.servlet.*;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

/**
 * Created by Administrator on 2014/12/5.
 * 过滤掉一些特殊字符
 */
public class StringFilter implements Filter {


    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //Enumeration params = servletRequest.getParameterNames();
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        String requestUrl = request.getRequestURI();
        String referer=request.getHeader("Referer");

        if (StringUtils.endsWith(requestUrl,".json") &&!SessionVOInterceptor.isInWhiteBillContains(requestUrl)){
            /*Subject subject = SecurityUtils.getSubject();
            boolean b= subject.isAuthenticated();
            Session session = subject.getSession();
            Object ooo= session.getAttribute("currentUser");
            Serializable x= session.getId();
            Object u111=session.getAttribute(SessionCacheSupport.USERLOGINID);*/
            HttpSession session=request.getSession();
            Object u=request.getSession().getAttribute(SessionCacheSupport.USERLOGINID+"__");
            String sessionidU = SessionCacheSupport.getRef(session.getId());
            UserSessionVO sessionVO1=null;
            if (u!=null){
                sessionVO1=SessionCacheSupport.get((String) u);
            }

            if (u==null && sessionVO1==null){
                String jsid="";
                Cookie[] cookie=request.getCookies();
                if (cookie!=null) {
                    for (Cookie cookie2 : cookie) {
                        if ("Jsid".equals(cookie2.getName())) {
                            jsid = cookie2.getValue();
                        }
                    }
                }
            if (StringUtils.isNotBlank(jsid)){
                List<UserSessionVO> sessionVOList=SessionCacheSupport.getOnlineUser();
                if (sessionVOList!=null) {
                    for (UserSessionVO sessionVO : sessionVOList) {
                        if (jsid.equals(sessionVO.getSessionID())) {
                            sessionVO.setServletSessionID(session.getId());
                            session.setAttribute(SessionCacheSupport.USERLOGINID + "__", sessionVO.getUsername());
                            SessionCacheSupport.putRef(session.getId(),jsid);
                            break;
                        }
                    }
                }
            }

            }else  if (sessionVO1==null&&u!=null){
                SessionCacheSupport.removeRef(session.getId());
                session.removeAttribute(SessionCacheSupport.USERLOGINID+"__");
            }else if (sessionVO1!=null && u==null){
                session.setAttribute(SessionCacheSupport.USERLOGINID + "__", sessionVO1.getUsername());
                SessionCacheSupport.putRef(session.getId(),sessionVO1.getSessionID());
            }

            u=session.getAttribute(SessionCacheSupport.USERLOGINID+"__");
            sessionidU = SessionCacheSupport.getRef(session.getId());
            if (u!=null){
                sessionVO1=SessionCacheSupport.get((String) u);
            }
            if (sessionVO1==null){
                //String re="{\"bool\":false,\"message\":\"sessionStatusFalse\",\"needFormat_\":\"need\",\"result\":\"未登录或者已过期\"}";
                SessionCacheSupport.removeRef(session.getId());
                session.removeAttribute(SessionCacheSupport.USERLOGINID+"__");
                org.apache.shiro.SecurityUtils.getSubject().logout();
                // 如果使用AjaxSupport里面的方法的话会报错，暂时性有fastjson原本的工具类来返回数据，未来需要干掉StringFilter类
                AjaxMessageResult ajaxMessageResult = new AjaxMessageResult(false, "sessionStatusFalse", "未登录或者已过期");
                AjaxResponse.sendText(response, JSON.toJSONString(ajaxMessageResult));
                /*AjaxSupport.sendFailText("sessionStatusFalse","未登录或者已过期");*/
                return;
            }
        }

        /*Object o=request.getHeader("X-Requested-With");
        if (request.getHeader("X-Requested-With") != null  && "XMLHttpRequest".equals( request.getHeader("X-Requested-With").toString())   ) {
            System.out.println("===");
        }*/
   //    int ii= response.getStatus();

        /*Map<String, String[]> map =request.getParameterMap();
        List<String> AjaxMode = SessionVOInterceptor.getParmByName(map, "AjaxMode", null);
        if(!ObjectUtil.isEmptyAll(AjaxMode)){//如果是ajax模式的请求
            String re="{\"bool\":false,\"message\":\"sessionStatusFalse\",\"needFormat_\":\"need\",\"result\":\"未登录或者已过期\"}";
            if (StringUtils.endsWith(requestUrl,"login.html")){
                request.getSession().removeAttribute(SessionCacheSupport.USERLOGINID);
                org.apache.shiro.SecurityUtils.getSubject().logout();
                AjaxResponse.sendText(response,re);
                //AjaxSupport.sendFailText("sessionStatusFalse","未登录或者已过期");
                return;
            }
            *//*if (!sessionB){
                AjaxResponse.sendText(response,re);
            }*//*
            *//*if (session==null){
                org.apache.shiro.SecurityUtils.getSubject().logout();
                AjaxResponse.sendText(response,re);
                return;
            }
            if (session.getAttribute(SessionCacheSupport.USERLOGINID)==null){
                org.apache.shiro.SecurityUtils.getSubject().logout();
                AjaxResponse.sendText(response,re);
                return;
            }
            if (SessionCacheSupport.getSessionVO()==null){
                request.getSession().removeAttribute(SessionCacheSupport.USERLOGINID);
                org.apache.shiro.SecurityUtils.getSubject().logout();
                AjaxResponse.sendText(response,re);
                return;
            }*//*

        }*/

        if (StringUtils.endsWith(requestUrl,".html")){
            String headerAccept = request.getHeader("Accept");
            if (("image/webp,*/*;q=0.8".equalsIgnoreCase(headerAccept)
                    ||("image/webp,image/*,*/*;q=0.8".equalsIgnoreCase(headerAccept))) && requestUrl.endsWith(".html")
                    && !requestUrl.endsWith("captchaActionlogin.do")) {//要排除掉两个验证码的请求
                return;
            }
        }

        filterChain.doFilter(request, response);
    }

    @Override
    public void destroy() {

    }


}
